<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | 王勇程 <laughskydragon@qq.com>                         |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\logic;

/**
 * 系统公告业务逻辑
 */
class Announcement extends LogicBase
{
    /**
     * 获取公告列表搜索条件
     */
    public function getWhere($data = [])
    {
        $where = [];
        
        // 搜索条件
        !empty($data['search_data']) && $where['title|content'] = ['like', '%'.$data['search_data'].'%'];
        
        // 类型条件
        !empty($data['type']) && $where['type'] = intval($data['type']);
        
        // 状态条件（未传入时不限定，后台默认“全部状态”）
        if (isset($data['announcement_status']) && $data['announcement_status'] !== '') {
            $where['announcement_status'] = intval($data['announcement_status']);
        }

        $where['status'] = !empty($data['status']) ? intval($data['status']) : 1;
        
        return $where;
    }
    
    /**
     * 获取公告列表
     * @param array $where 查询条件
     * @param string $field 查询字段
     * @param string $order 排序
     * @param mixed $paginate 分页参数
     * @return array
     */
    public function getAnnouncementList($where = [], $field = true, $order = '', $paginate = false)
    {
        return $this->modelAnnouncement->getList($where, $field, $order, $paginate);
    }
    
    /**
     * 获取公告列表（后台管理用）
     * @param array $where 查询条件
     * @param string $field 查询字段
     * @param string $order 排序
     * @param mixed $paginate 分页参数
     * @return array
     */
    public function getAnnouncementListForAdmin($where = [], $field = true, $order = '', $paginate = false)
    {
        return $this->modelAnnouncement->getList($where, $field, $order, $paginate);
    }
    
    /**
     * 获取公告详情
     * @param array $data 查询参数
     * @return array
     */
    public function getAnnouncementInfo($data = [])
    {
        $id = $data['id'] ?? 0;
        $userId = $data['user_id'] ?? 0;
        
        if ($id <= 0) {
            return [RESULT_ERROR, '公告ID不能为空'];
        }
        
        $info = $this->modelAnnouncement->getAnnouncementDetail($id, $userId);
        if (empty($info)) {
            return [RESULT_ERROR, '公告不存在或已下线'];
        }
        
        $info['type_text'] = $this->modelAnnouncement->getTypeOptions()[$info['type']] ?? '未知';
        $info['announcement_status_text'] = $this->modelAnnouncement->getStatusOptions()[$info['announcement_status']] ?? '未知';
        if (array_key_exists('status', $info)) {
            $info['status_text'] = intval($info['status']) === 1 ? '启用' : '禁用';
        }
        
        return [RESULT_SUCCESS, '获取成功', $info];
    }
    
    /**
     * 获取最新公告
     * @param array $data 查询参数
     * @return array
     */
    public function getLatestAnnouncement($data = [])
    {
        $limit = $data['limit'] ?? 1;
        $userId = $data['user_id'] ?? 0;
        
        $list = $this->modelAnnouncement->getLatestAnnouncementList($limit);
        
        if (!empty($list)) {
            // 获取用户已读状态
            if ($userId > 0) {
                $announcementIds = array_column($list, 'id');
                $readIds = $this->modelAnnouncementRead->getUserReadAnnouncementIds($userId, $announcementIds);
                
                foreach ($list as $key => $item) {
                    $item['is_read'] = in_array($item['id'], $readIds);
                    $item['type_text'] = $this->modelAnnouncement->getTypeOptions()[$item['type']] ?? '未知';
                    // 截取内容预览
                    $item['content_preview'] = mb_substr(strip_tags($item['content']), 0, 100) . '...';
                    
                    // 重新赋值修改后的数据
                    $list[$key] = $item;
                }
            }
        }
        
        return [RESULT_SUCCESS, '获取成功', $list];
    }
    
    /**
     * 标记公告为已读
     * @param array $data 参数
     * @return array
     */
    public function markAnnouncementAsRead($data = [])
    {
        $id = $data['id'] ?? 0;
        $userId = $data['user_id'] ?? 0;
        
        if ($id <= 0) {
            return [RESULT_ERROR, '公告ID不能为空'];
        }
        
        if ($userId <= 0) {
            return [RESULT_ERROR, '用户ID不能为空'];
        }
        
        // 检查公告是否存在
        $info = $this->modelAnnouncement->getInfo(['id' => $id, 'announcement_status' => $this->modelAnnouncement::ANNOUNCEMENT_STATUS_PUBLISHED]);
        if (empty($info)) {
            return [RESULT_ERROR, '公告不存在'];
        }
        
        $result = $this->modelAnnouncementRead->markAsRead($id, $userId);
        
        if ($result) {
            return [RESULT_SUCCESS, '标记成功'];
        } else {
            return [RESULT_ERROR, '标记失败'];
        }
    }
    
    /**
     * 批量标记公告为已读
     * @param array $data 参数
     * @return array
     */
    public function markMultipleAnnouncementsAsRead($data = [])
    {
        $ids = $data['ids'] ?? [];
        $userId = $data['user_id'] ?? 0;
        
        if (empty($ids)) {
            return [RESULT_ERROR, '公告ID列表不能为空'];
        }
        
        if ($userId <= 0) {
            return [RESULT_ERROR, '用户ID不能为空'];
        }
        
        $result = $this->modelAnnouncementRead->markMultipleAsRead($ids, $userId);
        
        if ($result) {
            return [RESULT_SUCCESS, '批量标记成功'];
        } else {
            return [RESULT_ERROR, '批量标记失败'];
        }
    }
    
    /**
     * 获取用户未读公告数量
     * @param array $data 参数
     * @return array
     */
    public function getUnreadAnnouncementCount($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        
        if ($userId <= 0) {
            return [RESULT_ERROR, '用户ID不能为空'];
        }
        
        $count = $this->modelAnnouncement->getUnreadCount($userId);
        
        return [RESULT_SUCCESS, '获取成功', ['count' => $count]];
    }
    
    /**
     * 添加公告
     * @param array $data 公告数据
     * @return array
     */
    public function addAnnouncement($data = [])
    {
        // 过滤掉fileselect字段，避免数据库报错
        unset($data['fileselect']);
        // 验证必填字段
        if (empty($data['title'])) {
            return [RESULT_ERROR, '公告标题不能为空'];
        }
        
        if (empty($data['content'])) {
            return [RESULT_ERROR, '公告内容不能为空'];
        }
        
        // 验证类型是否有效
        $typeOptions = $this->modelAnnouncement->getTypeOptions();
        $type = $data['type'] ?? 1;
        if (!isset($typeOptions[$type])) {
            return [RESULT_ERROR, '公告类型无效'];
        }
        
        // 设置默认值
        $data['type'] = $type;
        $data['announcement_status'] = $data['announcement_status'] ?? $this->modelAnnouncement::ANNOUNCEMENT_STATUS_DRAFT;
        $data['sort'] = $data['sort'] ?? 0;
        
        // 如果状态为已发布，设置发布时间
        if ($data['announcement_status'] == $this->modelAnnouncement::ANNOUNCEMENT_STATUS_PUBLISHED && empty($data['publish_time'])) {
            $data['publish_time'] = date('Y-m-d H:i:s');
        }
        
        $result = $this->modelAnnouncement->setInfo($data);
        
        if ($result) {
            return [RESULT_SUCCESS, '添加成功', ['id' => $result]];
        } else {
            return [RESULT_ERROR, '添加失败'];
        }
    }
    
    /**
     * 编辑公告
     * @param array $data 公告数据
     * @return array
     */
    public function editAnnouncement($data = [])
    {
        // 过滤掉fileselect字段，避免数据库报错
        unset($data['fileselect']);
        $id = $data['id'] ?? 0;
        
        if ($id <= 0) {
            return [RESULT_ERROR, '公告ID不能为空'];
        }
        
        // 检查公告是否存在
        $info = $this->modelAnnouncement->getInfo(['id' => $id]);
        if (empty($info)) {
            return [RESULT_ERROR, '公告不存在'];
        }
        
        // 验证类型是否有效
        if (!empty($data['type'])) {
            $typeOptions = $this->modelAnnouncement->getTypeOptions();
            if (!isset($typeOptions[$data['type']])) {
                return [RESULT_ERROR, '公告类型无效'];
            }
        }
        
        // 如果状态改为已发布且原来不是已发布状态，设置发布时间
        if (isset($data['announcement_status'])) {


            
            if ($data['announcement_status'] == $this->modelAnnouncement::ANNOUNCEMENT_STATUS_PUBLISHED 
                && $info['announcement_status'] != $this->modelAnnouncement::ANNOUNCEMENT_STATUS_PUBLISHED && empty($data['publish_time'])) {
                $data['publish_time'] = date('Y-m-d H:i:s');
            }
        }
        
        // 移除ID字段
        unset($data['id']);
        
        $result = $this->modelAnnouncement->updateInfo(['id' => $id], $data);
        
        if ($result !== false) {
            return [RESULT_SUCCESS, '编辑成功'];
        } else {
            return [RESULT_ERROR, '编辑失败'];
        }
    }
    
    /**
     * 删除公告
     * @param array $data 参数
     * @return array
     */
    public function deleteAnnouncement($data = [])
    {
        $id = $data['id'] ?? 0;
        
        if ($id <= 0) {
            return [RESULT_ERROR, '公告ID不能为空'];
        }
        
        // 检查公告是否存在
        $info = $this->modelAnnouncement->getInfo(['id' => $id]);
        if (empty($info)) {
            return [RESULT_ERROR, '公告不存在'];
        }
        
        $result = $this->modelAnnouncement->deleteInfo(['id' => $id]);
        
        if ($result) {
            // 同时删除相关的阅读记录
            $this->modelAnnouncementRead->deleteInfo(['announcement_id' => $id]);
            
            return [RESULT_SUCCESS, '删除成功'];
        } else {
            return [RESULT_ERROR, '删除失败'];
        }
    }
    
    /**
     * 发布公告
     * @param array $data 参数
     * @return array
     */
    public function publishAnnouncement($data = [])
    {
        $id = $data['id'] ?? 0;
        
        if ($id <= 0) {
            return [RESULT_ERROR, '公告ID不能为空'];
        }
        
        $result = $this->modelAnnouncement->publishAnnouncement($id);
        
        if ($result) {
            return [RESULT_SUCCESS, '发布成功'];
        } else {
            return [RESULT_ERROR, '发布失败'];
        }
    }
    
    /**
     * 下线公告
     * @param array $data 参数
     * @return array
     */
    public function offlineAnnouncement($data = [])
    {
        $id = $data['id'] ?? 0;
        
        if ($id <= 0) {
            return [RESULT_ERROR, '公告ID不能为空'];
        }
        
        $result = $this->modelAnnouncement->offlineAnnouncement($id);
        
        if ($result) {
            return [RESULT_SUCCESS, '下线成功'];
        } else {
            return [RESULT_ERROR, '下线失败'];
        }
    }
    
    /**
     * 获取公告统计数据
     * @param array $data 参数
     * @return array
     */
    public function getAnnouncementStatistics($data = [])
    {
        $type = $data['type'] ?? '';
        $startDate = $data['start_date'] ?? '';
        $endDate = $data['end_date'] ?? '';
        
        $where = [];
        if (!empty($type)) {
            $where['type'] = $type;
        }
        if (!empty($startDate)) {
            $where['publish_time'] = ['>=', $startDate];
        }
        if (!empty($endDate)) {
            $where['publish_time'] = ['<=', $endDate];
        }
        
        $totalCount = $this->modelAnnouncement->stat($where, 'count');
        $publishedCount = $this->modelAnnouncement->stat(array_merge($where, ['announcement_status' => 1]), 'count');
        $unpublishedCount = $this->modelAnnouncement->stat(array_merge($where, ['announcement_status' => 0]), 'count');
        
        $stats = [
            'total_count' => $totalCount,
            'published_count' => $publishedCount,
            'unpublished_count' => $unpublishedCount
        ];
        
        return [RESULT_SUCCESS, '获取成功', $stats];
    }
    
    /**
     * 获取公告类型选项
     * @return array
     */
    public function getTypeOptions()
    {
        return $this->modelAnnouncement->getTypeOptions();
    }
    
    /**
     * 获取公告状态选项
     * @return array
     */
    public function getStatusOptions()
    {
        return [
            0 => '草稿',
            1 => '已发布',
            2 => '已下线'
        ];
    }
    
    /**
     * 公告编辑
     * @param array $data 公告数据
     * @return array
     */
    public function announcementEdit($data = [])
    {
        $id = $data['id'] ?? 0;
        
        if (empty($id)) {
            // 新增公告
            return $this->addAnnouncement($data);
        } else {
            // 编辑公告
            return $this->editAnnouncement($data);
        }
    }
    
    /**
     * 公告删除
     * @param array $data 参数
     * @return array
     */
    public function announcementDel($data = [])
    {
        return $this->deleteAnnouncement($data);
    }
    
    /**
     * 设置公告排序
     * @param array $data 参数
     * @return array
     */
    public function setAnnouncementSortOrder($data = [])
    {
        $id = $data['id'] ?? 0;
        $sortOrder = $data['sort'] ?? 0;
        
        if (!$id) {
            return [RESULT_ERROR, '公告ID不能为空'];
        }
        
        $result = $this->modelAnnouncement->updateInfo(['id' => $id], ['sort' => $sortOrder]);
        
        if ($result !== false) {
            return [RESULT_SUCCESS, '排序设置成功'];
        } else {
            return [RESULT_ERROR, '排序设置失败'];
        }
    }
    
    /**
     * 导出公告列表
     * @param array $where 查询条件
     */
    public function exportAnnouncementList($where = [])
    {
        $list = $this->modelAnnouncement->getList($where, true, 'sort DESC, publish_time DESC, id DESC', false);
        
        // 这里可以实现导出逻辑，比如生成Excel文件
        // 暂时返回成功
        return [RESULT_SUCCESS, '导出成功'];
    }
}
